package com.lcredu.seckill.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.lcredu.seckill.config.RabbitMQConfigTopic;
import com.lcredu.seckill.config.RabbitSeckillMessageConfig;
import com.lcredu.seckill.pojo.SeckillMessage;
import com.lcredu.seckill.pojo.User;
import com.lcredu.seckill.service.GoodsService;
import com.lcredu.seckill.service.OrderService;
import com.lcredu.seckill.service.SeckillGoodsService;
import com.lcredu.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 黎长容
 * @date 2025-09-12 15:17
 */
@Service
@Slf4j
public class SeckillMQReceiver {
    //接收消息,完成下单
    @Resource
    public SeckillGoodsService seckillGoodsService;

    @Resource
    public OrderService orderService;
    
    @Resource
    public RedisTemplate redisTemplate;

    /*
        1. 将接收到的seckillMessage转为对象
        2. 取出用户和商品id值
        3. 调用秒杀方法
     */
    @RabbitListener(queues = RabbitSeckillMessageConfig.SECKILLMESSAGEQUEUE)
    public void ququeToSeckill(String seckilMessage) {
        System.out.println("注意这个消息--SeckillMQReceiver");
        log.info("接收到消息为={}", seckilMessage);
        SeckillMessage seckillMessage = JSONUtil.toBean(seckilMessage, SeckillMessage.class);
        User user = seckillMessage.getUser();
        long goodsId = seckillMessage.getGoodsId();
        GoodsVo goodsVo = seckillGoodsService.getGoodsVoById(goodsId);
        orderService.seckill(user, goodsVo);
    }


}
